import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { Form, message } from 'antd'
import FormCourtArbitratorLine from './FormCourtArbitratorLine'
import ArbitratorSelector from '../ArbitratorSelector/Index'
import { Split, TitleLine, TextLine, TextCell } from '@components/ApprovePre/Approve'
import { defaultProcedure } from '@src/assets/js/config'

const { List } = Form

export default class SecretaryInput extends Component {
  state = {
    asVisible: false,
    currentForm: null,
    currentArbitratorObj: {},
    currentArbitratorObjType: '', // 选择仲裁员方的类型
    currentArbitratorPath: [],
    currentArbitratoridPath: [],
    arbitratorSelectable: true,
    arbitrator1Selectable: true,
    arbitrator2Selectable: true,
    disabledIdList: []
  }

  // 设置编辑中的仲裁员
  setModifyArbitrator (form, arbpath, arbidpath, asVisible = true, type) {
    const name = form.current.getFieldValue(arbpath)
    const id = form.current.getFieldValue(arbidpath)
    this.setState({
      asVisible,
      currentArbitratorObj: { arbitrator: name || '', arbitratorid: id || '' },
      currentArbitratorObjType: type,
      currentForm: form,
      currentArbitratorPath: arbpath,
      currentArbitratoridPath: arbidpath
    })
  }

  // 限制重复选择仲裁员
  isHasSameSelected (arbitratorid, arbitrator) {
    const keyType = this.state.currentArbitratorObjType
    const formRef = this.state.currentForm.current
    // 当事人选择仲裁员
    if (['claimants', 'respondents'].indexOf(keyType) !== -1) {
      const path = this.state.currentArbitratoridPath
      const line = formRef.getFieldValue(path.slice(0, 2))
      const type = path[path.length - 1]
      const otherList = formRef.getFieldValue(keyType === 'claimants' ? ['respondents'] : ['claimants'])
      if (type === 'arbitratorid' && line.arbitratorid1 === arbitratorid) {
        message.warning('首席仲裁员与仲裁员不能为同一人')
        return true
      }
      if (type === 'arbitratorid1' && line.arbitratorid === arbitratorid) {
        message.warning('首席仲裁员与仲裁员不能为同一人')
        return true
      }
      if (type === 'arbitratorid1') {
        const ids = []
        otherList.forEach(li => {
          if (ids.indexOf(li.arbitratorid1) === -1) {
            ids.push(li.arbitratorid1)
          }
        })
        if (ids.length === 1 && ids[0] === arbitratorid) {
          message.warning(`仲裁员 ${arbitrator} 已被选择，请重新选择仲裁员`)
          return true
        }
      }
    }
    return false
  }

  // 改变仲裁员选择器
  onChangeArbitrator ({ arbitratorid, arbitrator }) {
    this.setState({
      disabledIdList: []
    })
    const isNormal = this.props.caseDetail.procedure === defaultProcedure
    if (isNormal && this.state.currentArbitratorObjType && arbitratorid && this.isHasSameSelected(arbitratorid, arbitrator)) {
      return false
    }
    const arbPath = this.state.currentArbitratorPath
    const arbidPath = this.state.currentArbitratoridPath
    const current = this.state.currentForm.current
    const nP = { [arbPath[0]]: current.getFieldValue(arbPath[0]) }
    const iP = { [arbidPath[0]]: current.getFieldValue(arbidPath[0]) }
    let name = nP[arbPath[0]]
    let id = iP[arbidPath[0]]
    for (let i = 1; i < arbPath.length - 1; i++) {
      name = name[arbPath[i]]
    }
    if (arbPath.length > 1) {
      name[arbPath[arbPath.length - 1]] = arbitrator
    } else {
      nP[arbPath[0]] = arbitrator
    }
    for (let i = 1; i < arbidPath.length - 1; i++) {
      id = id[arbidPath[i]]
    }
    if (arbidPath.length > 1) {
      id[arbidPath[arbidPath.length - 1]] = arbitratorid
    } else {
      iP[arbidPath[0]] = arbitratorid
    }
    const data = {
      ...nP,
      ...iP
    }
    current.setFieldsValue(data)
    this.setState({
      currentArbitratorPath: [],
      currentArbitratoridPath: [],
      currentArbitratorObj: {},
      currentArbitratorObjType: '',
      currentForm: null
    })
  }

  // 渲染仲裁员列表
  renderArbitratorList (formRef, name = '') {
    return (
      <List name={name}>
        {
          fields => {
            return fields.map(field => <FormCourtArbitratorLine setModifyArbitrator={(...p) => this.setModifyArbitrator(...p)} key={field.key} paramName={name} field={field} formRef={formRef} unSelect={o => this.onChangeArbitrator(o)} caseDetail={this.props.caseDetail} />)
          }
        }
      </List>
    )
  }

  render () {
    const { formCourt: c } = this.props.instance
    return (
      <div>
        <ArbitratorSelector value={this.state.currentArbitratorObj} visible={this.state.asVisible} caseDetail={this.props.caseDetail} hide={() => this.setState({ asVisible: false, disabledIdList: [] })} onChange={o => this.onChangeArbitrator(o)} disabledIdList={this.state.disabledIdList} />
        <TextLine>
          <TextCell>操作人：{this.props.userInfo.realname}</TextCell>
          <Split />
          <TextCell>组庭类型：{c.type}</TextCell>
        </TextLine>
        <TitleLine title='申请人' />
        {this.renderArbitratorList(this.props.formRef, 'claimants')}
        <TitleLine title='被申请人' />
        {this.renderArbitratorList(this.props.formRef, 'respondents')}
      </div>
    )
  }
}

SecretaryInput.proptypes = {
  caseDetail: PropTypes.object,
  userInfo: PropTypes.object,
  instance: PropTypes.object,
  formRef: PropTypes.object
}

SecretaryInput.defaultProps = {
  caseDetail: {},
  userInfo: {},
  instance: {},
  formRef: {}
}
